using System.Data;
using System.Data.SqlClient;
using CoreLibrary.Date;
using CoreLibrary.Sql;

namespace CoreLibrary.Messaging.Sql {

    public class CountMessage : ISqlScalar<int> {

        private readonly string _tableName;
        private readonly ListMessageQuery _query;

        public CountMessage(string tableName, ListMessageQuery query) {
            _tableName = tableName;
            _query = query;
        }

        public string GetSQL() {
            var statusParams = StringUtil.Join(", ", _query.MessageStatuses, true);
            return string.Format(@"
                select  count(*)
                from    {0}
                where   status in ({1}) and
                        date_scheduled >= @scheduledFrom and
                        date_scheduled <= @scheduledTo 
                ",  
                _tableName, 
                statusParams
            );
        }

        public void SetParameters(SqlCommand command) {
            command.Parameters.Add("@scheduledFrom", SqlDbType.DateTime).Value = 
                DateUtil.ConvertMillisSinceEpochToDateTime(_query.ScheduledDateFrom, DateUtil.Epoch);
            command.Parameters.Add("@scheduledTo", SqlDbType.DateTime).Value = 
                DateUtil.ConvertMillisSinceEpochToDateTime(_query.ScheduledDateTo, DateUtil.Year2050);
        }

        public int GetResult(SqlConnection conn, object result) {
            return (int)result;
        }

    }
}